package controle;

import interfaceUsuario.TCPPPChat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


import sessao.SessaoChat;

public class ControleChat {

	public SessaoChat sessao;
	public static TCPPPChat tcp;

	public ControleChat(TCPPPChat tcp) {
		this.tcp = tcp;
		this.sessao = new SessaoChat("localhost", 1234, true, tcp);
		tcp = new TCPPPChat();
	}

	public void invoke() {

	}

	public void executa() {
		String s;

		while (true) {
			int status = this.sessao.statusConexao;
			switch (status) {
			case 3:
				try {
					if (this.sessao.ehHost) {
						tcp.hostServer = new ServerSocket(this.sessao.porta);
						tcp.socket = tcp.hostServer.accept();
					}

					else {
						tcp.socket = new Socket(this.sessao.hostIP,
								this.sessao.porta);
					}

					tcp.entrada = new BufferedReader(new InputStreamReader(
							tcp.socket.getInputStream()));
					tcp.saida = new PrintWriter(tcp.socket.getOutputStream(),
							true);
					this.sessao.alterarStatusTS(tcp.CONECTADO, true);
				} catch (IOException e) {
					tcp.limpando();
					this.sessao.alterarStatusTS(tcp.DESCONECTADO, false);
				}
				break;

			case 4:
				try {
					if (this.sessao.enviar.length() != 0) {
						tcp.saida.print(this.sessao.enviar);
						tcp.saida.flush();
						this.sessao.enviar.setLength(0);
						this.sessao.alterarStatusTS(tcp.NULL, true);
					}

					if (tcp.entrada.ready()) {
						s = tcp.entrada.readLine();
						if ((s != null) && (s.length() != 0)) {
							if (s.equals(tcp.FIM_SESSAO)) {
								this.sessao.alterarStatusTS(
										this.tcp.DESCONECTANDO, true);
							} else {
								this.sessao.adicionarString("Entrada: " + s
										+ "\n");
								this.sessao
										.alterarStatusTS(this.tcp.NULL, true);
							}
						}
					}
				} catch (IOException e) {

					tcp.limpando();

					this.sessao.alterarStatusTS(this.tcp.DESCONECTANDO, false);
				}
				break;

			case 2:
				tcp.saida.print(this.tcp.FIM_SESSAO);
				tcp.saida.flush();
				tcp.limpando();

				this.sessao.alterarStatusTS(this.tcp.DESCONECTADO, true);
				break;

			default:
				break;
			}
		}
	}
}
